package com.gecba.system.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.gecba.modular.jpa.utils.StringUtils;
import com.gecba.system.entity.SysOssFile;
import com.gecba.system.service.SysOssFileService;
import com.gecba.system.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("/image")
public class SysUploadController {

    @Autowired
    private SysOssFileService sysOssFileService;

    /**
     * 上传文件
     * @param request
     * @return
     */
    @PostMapping(value = "/upload")
    public Result<?> upload(MultipartHttpServletRequest request){

        Iterator<String> fileNames = request.getFileNames();
        List<MultipartFile> multipartFileList = null;
        while (fileNames.hasNext()){
            multipartFileList = request.getFiles(fileNames.next());
        }
        if(CollectionUtil.isEmpty(multipartFileList)){
            return Result.error("没有文件");
        }
        List<SysOssFile> sysOssFileList = multipartFileList.stream().filter(Objects::nonNull)
                .map(multipartFile -> sysOssFileService.upload(multipartFile))
                .collect(Collectors.toList());
        return  Result.OK(sysOssFileList);
    }


    /**
     * 删除文件
     * @param sysOssFile
     * @return
     */
    @DeleteMapping("/delete")
    public Result<?> delete(SysOssFile sysOssFile){
        String fileName = sysOssFile.getFileName();
        if(StringUtils.isBlank(fileName)){
            log.error("删除图片的文件名称为空");
        }
        int delete = sysOssFileService.deleteByFileName(fileName);
        if(delete>0){
            return Result.OK();
        }else {
            return Result.error("文件删除失败");
        }

    }
}
